package com.cash.app.ui.order

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant
import com.cash.app.constant.AppConstant.OS_AUDIT_FAILED
import com.cash.app.constant.AppConstant.OS_FAILURE_PAYMENT
import com.cash.app.constant.AppConstant.OS_MODIFY_BANK_INFO
import com.cash.app.constant.AppConstant.OS_OVERDUE
import com.cash.app.constant.AppConstant.OS_PENDING_PAYMENT
import com.cash.app.constant.AppConstant.OS_PENDING_REPAY
import com.cash.app.constant.AppConstant.OS_REPAID_REPAYMENT
import com.cash.app.constant.AppConstant.OS_UNDER_REVIEW
import com.cash.app.constant.AppConstant.REPAY_CHANNEL_APP
import com.cash.app.constant.AppConstant.REPAY_CHANNEL_BROWSER
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcLoanInfoBinding
import com.cash.app.manager.GlobalConfigManager
import com.cash.app.ui.auth.AuthBankActivity
import com.cash.app.ui.loan.LoanConfirmActivity
import com.cash.app.ui.loan.LoanConfirmResultActivity
import com.cash.app.ui.order.model.LoanDetailResponse
import com.cash.app.ui.other.RepayActivity
import com.cash.app.utils.NumberUtils
import com.cash.app.utils.ThirdAppUtils
import com.cash.app.utils.hide
import com.cash.app.utils.visible

class LoanInfoActivity : BaseActivity() {

    private lateinit var binding: AcLoanInfoBinding
    private val viewModel: LoanInfoViewModel by viewModels()

    companion object {
        const val EXTRA_ORDER_ID = "EXTRA_ORDER_ID"
        fun start(
            context: Context, orderId: Int
        ) {
            val intent = Intent(context, LoanInfoActivity::class.java).apply {
                putExtra(EXTRA_ORDER_ID, orderId)
            }
            context.startActivity(intent)
        }
    }

    override val isFitsSystemWindows: Boolean
        get() = false

    override val isFitNavigationBarInsets: Boolean
        get() = true

    override val statusBarTextDark: Boolean
        get() = false

    override val statusBarColor: Int
        get() = R.color.transparent

    override fun setViewBind() {
        binding = AcLoanInfoBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View {
        return binding.root
    }

    override fun getAppActionBar(): AppActionBar? {
        return binding.actionBar
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initObservers()
        loadData()
    }

    private fun initObservers() {
        viewModel.loanInfo.observe(this) { response ->
            updateUI(response)
        }
        viewModel.repayInfo.observe(this) { response ->
            binding.btnBottom.visible()
            binding.btnBottom.text = getString(R.string.repay_now)
            binding.btnBottom.setOnClickListener {
                if (response.jump_to_url.isEmpty()) {
                    Toast.makeText(this, getString(R.string.repay_url_error), Toast.LENGTH_SHORT)
                        .show()
                    return@setOnClickListener
                }
                when (response.repay_channel) {
                    REPAY_CHANNEL_APP -> {
                        RepayActivity.start(this, response.jump_to_url)
                    }

                    REPAY_CHANNEL_BROWSER -> {
                        ThirdAppUtils.openInSystemBrowser(this, response.jump_to_url)
                    }

                    else -> {
                        ThirdAppUtils.openInSystemBrowser(this, response.jump_to_url)
                    }
                }
            }
        }
        viewModel.fastApplyData.observe(this) { response ->
            LoanConfirmResultActivity.start(this, response.remark)
        }
    }

    private fun loadData() {
        val orderId = intent.getIntExtra(EXTRA_ORDER_ID, -1)
        if (orderId != -1) {
            viewModel.getLoanDetail(orderId)
        } else {
            Toast.makeText(this, "Order Id error", Toast.LENGTH_SHORT).show()
        }
    }

    private fun jumpToLoanApply(product: LoanDetailResponse) {
        if (GlobalConfigManager.isFastApplyEnabled()) {
            viewModel.fastApply(product.p_id)
        } else {
            LoanConfirmActivity.start(
                this,
                product.p_id,
                product.order_money,
                product.order_peroid,
                product.p_name,
                product.p_icon
            )
        }
    }

    private fun updateUI(loanDetail: LoanDetailResponse) {
        binding.infoBgCl.setBackgroundResource(getOrderStatusBackground(loanDetail.order_status))
        binding.tvOrderStatus.text = AppConstant.getOrderStatusText(loanDetail.order_status)

        if (loanDetail.order_status == OS_PENDING_REPAY || loanDetail.order_status == OS_OVERDUE) {
            binding.tvLineOfCredit.text = getString(
                R.string.unit_rupee_prefix,
                NumberUtils.toRupeeWithComma(loanDetail.repay_info.r_total_money)
            )

        } else {
            binding.tvLineOfCredit.text = getString(
                R.string.unit_rupee_prefix, NumberUtils.toRupeeWithComma(loanDetail.order_money)
            )
        }

        binding.tvTenure.text = getString(R.string.unit_tenure, loanDetail.order_peroid.toString())
        binding.tvLoanDate.text = loanDetail.created_at_string
        binding.tvBankAccount.text = NumberUtils.maskBankCard(loanDetail.bank_card)

        if (loanDetail.order_status == OS_REPAID_REPAYMENT && loanDetail.can_reloan) {
            binding.btnBottom.visible()
            binding.btnBottom.text = getString(R.string.repay_again)
            binding.btnBottom.setOnClickListener {
                jumpToLoanApply(loanDetail)
            }
        } else if (loanDetail.order_status == OS_OVERDUE || loanDetail.order_status == OS_PENDING_REPAY) {
            viewModel.getRepayUrl(loanDetail.o_id)
        } else if (loanDetail.order_status == OS_MODIFY_BANK_INFO) {
            binding.btnBottom.visible()
            binding.btnBottom.text = getString(R.string.bind_bank_now)
            binding.btnBottom.setOnClickListener {
                AuthBankActivity.start(this)
            }
        } else {
            binding.btnBottom.hide()
        }
    }

    private fun getOrderStatusBackground(status: Int): Int {
        return when (status) {
            OS_UNDER_REVIEW -> R.drawable.loan_os_bg_under_review
            OS_AUDIT_FAILED -> R.drawable.loan_os_bg_audit_failed
            OS_PENDING_PAYMENT -> R.drawable.loan_os_bg_pending_payment
            OS_FAILURE_PAYMENT -> R.drawable.loan_os_bg_failure_payment
            OS_PENDING_REPAY -> R.drawable.loan_os_bg_pending_repay
            OS_REPAID_REPAYMENT -> R.drawable.loan_os_bg_repaid
            OS_OVERDUE -> R.drawable.loan_os_bg_overdue
            OS_MODIFY_BANK_INFO -> R.drawable.loan_os_bg_modify_bank
            else -> R.drawable.loan_os_bg_repaid
        }
    }
}